<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use App\Http\Controllers\QrCodeController;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 活动单位表
 */

class AnswerActivityUnit extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'answer_activity_unit';


    /**
     * 获取单位性质
     * $type 单位性质    1 图书馆  2 文化馆  3 博物馆
     */
    public function getNatureName($type = null)
    {
        $data = ['1' => '图书馆', '文化馆', '博物馆'];
        if ($type) {
            return $data[$type];
        }
        return $data;
    }
    /**
     * 获取单位性质 id
     * $type 单位性质    1 图书馆  2 文化馆  3 博物馆
     */
    public function getNatureIdByName($name)
    {
        $data = ['图书馆' => 1, '文化馆' => 2, '博物馆' => 3];
        return $data[$name];
    }


    /*关联活动区域*/
    public function conArea()
    {
        return $this->hasOne(AnswerActivityArea::class, 'id', 'area_id');
    }

    /**
     * 获取一个默认单位
     */
    public function getDefaultUnit($act_id)
    {
        $unit_id = $this->where('act_id', $act_id)->where('is_default', 1)->where('is_del', 1)->value('id');
        if ($unit_id) {
            return $unit_id;
        }
        $unit_id = $this->where('act_id', $act_id)->where('is_del', 1)->orderBy('order')->value('id');
        if ($unit_id) {
            return $unit_id;
        }
    }

    /**
     * 是否配置单位
     * @param act_id
     */
    public static function isHaveUnit($act_id)
    {
        $unit_info = self::where('act_id', $act_id)->where('is_del', 1)->first();
        if (empty($unit_info)) {
            return '未配置单位，请先配置';
        }
        return true;
    }

    /**
     * 限制单位赠言个数
     * @param $content
     */
    public function limitWords($content)
    {
        if (!empty($content) && mb_strlen($content) > 50) {
            return '单位赠言最多50字，请重新输入';
        }
        return true;
    }

    /**
     * 根据单位id获取单位名称
     * @param $content
     */
    public function getUnitNameByUnitId($unit_id)
    {
        return $this->where('id', $unit_id)->value('name');
    }
    /**
     * 根据区域id，获取单位id
     * @param act_id 活动id
     * @param area_id 区域id
     */
    public function getUnitIdByAreaId($act_id, $area_id)
    {
        return $this->where('act_id', $act_id)->where('area_id', $area_id)->pluck('id')->toArray(); //获取一列数据
    }


    /**
     * 判断活动是否允许添加区域
     * @param act_id 活动id
     */
    public function isAllowAddUnit($act_id)
    {
        $res = AnswerActivity::where('id', $act_id)->where('is_del', 1)->value('node'); //node  2 单位联盟   3 区域联盟
        if (empty($res)) {
            return '此活动不存在';
        }
        if ($res == 1) {
            return '此活动为独立活动模式，不允许操作单位';
        }
        return true;
    }

    /**
     * 获取单位列表
     * @param field int 获取字段信息  数组
     * @param act_id int 活动id
     * @param page int 当前页
     * @param limit int 分页大小
     * @param area_id int 区域id
     * @param unit_id int 单位id  只查满足条件的单位名称
     * @param nature int 单位性质   1 图书馆  2 文化馆  3 博物馆
     * @param start_time datetime 创建时间范围搜索(开始)
     * @param end_time datetime 创建时间范围搜索(结束)
     * @param keywords string 搜索关键词(类型名称)
     *
     * @param lon int 经度 选填
     * @param lat int 纬度 选填
     */
    public function lists($field, $act_id, $keywords, $area_id, $nature, $unit_id = [], $start_time = null, $end_time = null,  $lon = null, $lat = null, $limit = 10)
    {
        if (empty($field)) {
            $field = [
                'id', 'act_id', 'area_id', 'nature', 'name', 'img', 'intro', 'words', 'letter', 'is_default', 'province',
                'city', 'district', 'address', 'qr_url', 'order', 'create_time', 'lon', 'lat',
            ];
        }
        if ($lon && $lat) {
            $field[] = DB::raw("round((2 * 6378.137 * ASIN(SQRT(POW( SIN( PI()*( $lat- lat )/ 360 ), 2 )+ COS( PI()* $lat / 180 )* COS( lat * PI()/ 180 )* POW( SIN( PI()*( $lon- lon )/ 360 ), 2 )))) * 1000) as distance");
        }
        $res = $this->select($field)
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('name', 'like', '%' . $keywords . '%');
                }
            })->where(function ($query) use ($act_id, $area_id, $nature, $unit_id, $start_time, $end_time) {
                if ($act_id) {
                    $query->where('act_id', $act_id);
                }
                if ($area_id) {
                    $query->where('area_id', $area_id);
                }
                if ($nature) {
                    $query->where('nature', $nature);
                }
                if ($unit_id) {
                    $query->whereIn('id', $unit_id);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('create_time', [$start_time, $end_time]);
                }
            })
            ->with('conArea')
            ->where('is_del', 1);

        if ($lon && $lat) {
            $res = $res->orderBy('distance');
        }
        $res = $res->orderBy('order')
            ->orderBy('id')
            ->paginate($limit)
            ->toArray();

        $controllerObj = new Controller();
        $res = $controllerObj->disPageData($res);

        return $res;
    }

    /**
     * 获取单位详情
     * @param qr_code int 二维码code信息
     */
    public function getDetailByQrCode($qr_code, $field = [])
    {
        if (empty($field)) {
            $field = ['id', 'act_id', 'area_id', 'nature', 'name', 'img', 'intro', 'words', 'letter', 'is_default', 'province', 'city', 'district', 'address', 'qr_url', 'order', 'create_time'];
        }
        $res = $this->select($field)
            ->where('qr_code', $qr_code)
            ->where('is_del', 1)
            ->first();

        return $res;
    }


    /**
     * 获取单位详情
     * @param id int 单位id
     */
    public function detail($id, $field = [])
    {
        if (empty($field)) {
            $field = ['id', 'act_id', 'area_id', 'nature', 'name', 'img', 'intro', 'words', 'letter', 'is_default', 'province', 'city', 'district', 'address', 'qr_url', 'order', 'create_time'];
        }
        $res = $this->select($field)
            ->with('conArea')
            ->where('is_del', 1)
            ->where(function ($query) use ($id) {
                if ($id) {
                    $query->where('id', $id);
                }
            })
            ->first();

        //获取单位区域
        if (!empty($res)) {
            $res['nature_name'] = $this->getNatureName($res['nature']);
            $res['area_name'] = !empty($res['conArea']['name']) ?  $res['conArea']['name'] : '';
            unset($res['conArea']);
        }

        return $res;
    }


    /**
     * 随机获取一个单位详情
     * @param act_id int 单位id
     */
    public function detailByActId($act_id, $field = [])
    {
        if (empty($field)) {
            $field = ['id', 'act_id', 'area_id', 'nature', 'name', 'img', 'intro', 'words', 'letter', 'is_default', 'province', 'city', 'district', 'address', 'qr_url', 'order', 'create_time'];
        }
        $res = $this->select($field)
            ->where('is_del', 1)
            ->where('act_id', $act_id)
            ->first();

        return $res;
    }


    /**
     * 获取单位统计数据
     *  //馆内答题   答题进度：  1/5      爬楼梯：答题进度 52/100        轮次：已答轮次：5轮
     */
    public function unitAnswerNumber($pattern, $user_guid, $act_id, $unit_id)
    {
        $unit_id = $unit_id ?: 0;
        if ($pattern == 1 || $pattern == 3) {
            $answerActivityObj = new AnswerActivity();
            $model = $answerActivityObj->getAnswerTotalRecordModel($pattern);
            //  dump($model);
            return $model->where('user_guid', $user_guid)->where('act_id', $act_id)->where('unit_id', $unit_id)->value('correct_number');
        } else if ($pattern == 2) {
            //返回的是轮次
            return AnswerActivityUserCorrectNumber::where('user_guid', $user_guid)->where('act_id', $act_id)->where('unit_id', $unit_id)->count();
        }
    }

    /**
     * 从基础数据库中选择单位到活动里面
     * @param act_id int 活动id
     * @param unit_ids int 基础数据单位id  多个逗号拼接
     */
    public function selectBaseUnit($act_id, $unit_ids)
    {
        $unit_ids = explode(',', $unit_ids);
        $answerActivityBaseUnitModel = new AnswerActivityBaseUnit();
        $qrCodeObj = new QrCodeController();
        foreach ($unit_ids as $key => $val) {
            $unit_info = $answerActivityBaseUnitModel->where('id', $val)->where('is_del', 1)->first();
            if (empty($unit_info)) {
                continue;
            }
            //判断当前图书馆，当前活动是否存在
            $condition[] = ['act_id', '=', $act_id];
            $is_exists = $this->nameIsExists($unit_info->name, 'name', null, 1, $condition);
            if ($is_exists) {
                continue;
            }
            //添加到当前活动
            //生成二维码
            $qr_code = $qrCodeObj->getQrCode('answer_activity_unit');
            if ($qr_code === false) {
                Log::error("答题活动单位二维码生成失败,请手动生成");
                continue;
            }
            $obj = new Controller();
            $qr_data = $obj->getDomainName() . '/' . config('other.project_name') . 'wx/pGames/gameLoading/index?from=readshare_activity&token=' . $qr_code; //渝中区二维码的链接  扫码跳转渝中区二维码

            $qr_url = $qrCodeObj->setQr($qr_data, true, 360, 1);
            $data['act_id'] = $act_id;
            $data['qr_code'] = $qr_code;
            $data['qr_url'] = $qr_url;
            $data['nature'] = $unit_info['nature'];
            $data['name'] = $unit_info['name'];
            $data['img'] = $unit_info['img'];
            $data['intro'] = $unit_info['intro'];
            $data['tel'] = $unit_info['tel'];
            $data['contacts'] = $unit_info['contacts'];
            $data['words'] = $unit_info['words'];
            $data['letter'] = $unit_info['letter'];
            $data['province'] = $unit_info['province'];
            $data['city'] = $unit_info['city'];
            $data['district'] = $unit_info['district'];
            $data['address'] = $unit_info['address'];
            $data['lon'] = $unit_info['lon'];
            $data['lat'] = $unit_info['lat'];
            //添加到活动
            $obj = new self();
            $obj->add($data);
        }
    }


}
